/**
 * XL-Payment 订单管理
 * 用于处理订单的创建、更新、查询和状态同步
 */

// 存储键前缀
const STORAGE_KEY_PREFIX = 'xl_payment_order_';
// 待处理订单列表键
const PENDING_ORDERS_KEY = 'xl_payment_pending_orders';

export class OrderManager {
  constructor({ store, config }) {
    this.store = store;
    this.config = config;
  }
  
  /**
   * 保存订单到存储
   * @param {Object} order 订单对象
   * @returns {Promise} 保存结果
   */
  async saveOrder(order) {
    if (!order || !order.id) {
      throw new Error('订单信息不完整');
    }
    
    try {
      // 保存订单到本地存储
      const storageKey = `${STORAGE_KEY_PREFIX}${order.id}`;
      uni.setStorageSync(storageKey, JSON.stringify(order));
      
      // 添加到待处理订单列表
      if (order.status !== 'PAID' && 
          order.status !== 'SUCCESS' && 
          order.status !== 'CLOSED' && 
          order.status !== 'FAILED' && 
          order.status !== 'REFUNDED') {
        const pendingOrders = this.getPendingOrders();
        if (!pendingOrders.includes(order.id)) {
          pendingOrders.push(order.id);
          uni.setStorageSync(PENDING_ORDERS_KEY, JSON.stringify(pendingOrders));
        }
      }
      
      // 更新活跃订单状态
      this.store.addActiveOrder(order);
      
      return { success: true };
    } catch (error) {
      console.error('保存订单失败:', error);
      return { success: false, error };
    }
  }
  
  /**
   * 获取订单信息
   * @param {String} orderId 订单ID
   * @returns {Object|null} 订单对象
   */
  async getOrder(orderId) {
    if (!orderId) {
      return null;
    }
    
    try {
      const storageKey = `${STORAGE_KEY_PREFIX}${orderId}`;
      const orderData = uni.getStorageSync(storageKey);
      
      if (orderData) {
        return JSON.parse(orderData);
      }
      
      return null;
    } catch (error) {
      console.error('获取订单失败:', error);
      return null;
    }
  }
  
  /**
   * 获取所有本地订单
   * @returns {Array} 订单列表
   */
  async getAllOrders() {
    try {
      const orders = [];
      const storage = uni.getStorageInfoSync();
      
      for (const key of storage.keys) {
        if (key.startsWith(STORAGE_KEY_PREFIX)) {
          const orderData = uni.getStorageSync(key);
          if (orderData) {
            try {
              const order = JSON.parse(orderData);
              orders.push(order);
            } catch (e) {
              // 忽略无效数据
            }
          }
        }
      }
      
      return orders;
    } catch (error) {
      console.error('获取所有订单失败:', error);
      return [];
    }
  }
  
  /**
   * 更新订单信息
   * @param {Object} order 订单对象
   * @returns {Promise} 更新结果
   */
  async updateOrder(order) {
    if (!order || !order.id) {
      throw new Error('订单信息不完整');
    }
    
    try {
      // 获取原订单
      const existingOrder = await this.getOrder(order.id);
      
      // 合并订单信息
      const updatedOrder = {
        ...existingOrder,
        ...order,
        updatedAt: new Date().toISOString()
      };
      
      // 保存更新后的订单
      const storageKey = `${STORAGE_KEY_PREFIX}${order.id}`;
      uni.setStorageSync(storageKey, JSON.stringify(updatedOrder));
      
      // 更新待处理订单列表
      const isTerminalState = ['PAID', 'SUCCESS', 'CLOSED', 'FAILED', 'REFUNDED'].includes(updatedOrder.status);
      if (isTerminalState) {
        const pendingOrders = this.getPendingOrders();
        const index = pendingOrders.indexOf(order.id);
        if (index !== -1) {
          pendingOrders.splice(index, 1);
          uni.setStorageSync(PENDING_ORDERS_KEY, JSON.stringify(pendingOrders));
        }
      }
      
      // 更新活跃订单状态
      this.store.updateActiveOrder(order.id, updatedOrder);
      
      return { success: true, order: updatedOrder };
    } catch (error) {
      console.error('更新订单失败:', error);
      return { success: false, error };
    }
  }
  
  /**
   * 删除订单
   * @param {String} orderId 订单ID
   * @returns {Promise} 删除结果
   */
  async deleteOrder(orderId) {
    if (!orderId) {
      return { success: false, error: '订单ID不能为空' };
    }
    
    try {
      // 从存储中删除
      const storageKey = `${STORAGE_KEY_PREFIX}${orderId}`;
      uni.removeStorageSync(storageKey);
      
      // 从待处理列表中删除
      const pendingOrders = this.getPendingOrders();
      const index = pendingOrders.indexOf(orderId);
      if (index !== -1) {
        pendingOrders.splice(index, 1);
        uni.setStorageSync(PENDING_ORDERS_KEY, JSON.stringify(pendingOrders));
      }
      
      // 从活跃订单中移除
      this.store.removeActiveOrder(orderId);
      
      return { success: true };
    } catch (error) {
      console.error('删除订单失败:', error);
      return { success: false, error };
    }
  }
  
  /**
   * 获取待处理订单ID列表
   * @returns {Array} 订单ID列表
   */
  getPendingOrders() {
    try {
      const pendingOrdersData = uni.getStorageSync(PENDING_ORDERS_KEY);
      return pendingOrdersData ? JSON.parse(pendingOrdersData) : [];
    } catch (error) {
      console.error('获取待处理订单列表失败:', error);
      return [];
    }
  }
  
  /**
   * 同步待处理订单状态
   * @returns {Promise} 同步结果
   */
  async syncPendingOrders() {
    try {
      const pendingOrderIds = this.getPendingOrders();
      
      // 如果没有待处理订单，直接返回
      if (!pendingOrderIds || pendingOrderIds.length === 0) {
        return { success: true, synced: 0 };
      }
      
      // 获取所有待处理订单
      const pendingOrders = [];
      for (const orderId of pendingOrderIds) {
        const order = await this.getOrder(orderId);
        if (order) {
          pendingOrders.push(order);
        }
      }
      
      // 检查是否有超时订单
      const now = Date.now();
      const orderTimeout = this.config.orderTimeout * 60 * 1000; // 转换为毫秒
      const ordersToSync = [];
      
      for (const order of pendingOrders) {
        // 检查订单创建时间
        const createdTime = new Date(order.createdAt).getTime();
        const isExpired = now - createdTime > orderTimeout;
        
        if (isExpired && order.status !== 'CLOSED' && order.status !== 'FAILED') {
          // 标记为超时关闭
          order.status = 'CLOSED';
          order.closedAt = new Date().toISOString();
          order.closeReason = '订单超时自动关闭';
          await this.updateOrder(order);
        } else if (!['PAID', 'SUCCESS', 'CLOSED', 'FAILED', 'REFUNDED'].includes(order.status)) {
          // 需要同步状态的订单
          ordersToSync.push(order);
        }
      }
      
      // 如果有需要同步的订单，触发支付实例去同步
      if (ordersToSync.length > 0) {
        // 返回需要同步的订单，由支付实例进行处理
        return { 
          success: true, 
          synced: pendingOrders.length - ordersToSync.length,
          pendingSync: ordersToSync.length,
          orders: ordersToSync
        };
      }
      
      return { success: true, synced: pendingOrders.length };
    } catch (error) {
      console.error('同步待处理订单失败:', error);
      return { success: false, error };
    }
  }
  
  /**
   * 清理过期订单
   * @param {Number} days 保留天数，默认30天
   * @returns {Promise} 清理结果
   */
  async cleanExpiredOrders(days = 30) {
    try {
      const allOrders = await this.getAllOrders();
      const now = Date.now();
      const expiryTime = days * 24 * 60 * 60 * 1000; // 天数转为毫秒
      let cleanCount = 0;
      
      for (const order of allOrders) {
        // 获取订单的最后更新时间
        let lastUpdateTime;
        if (order.updatedAt) {
          lastUpdateTime = new Date(order.updatedAt).getTime();
        } else if (order.paidAt) {
          lastUpdateTime = new Date(order.paidAt).getTime();
        } else if (order.closedAt) {
          lastUpdateTime = new Date(order.closedAt).getTime();
        } else {
          lastUpdateTime = new Date(order.createdAt).getTime();
        }
        
        // 检查是否过期
        if (now - lastUpdateTime > expiryTime) {
          await this.deleteOrder(order.id);
          cleanCount++;
        }
      }
      
      return { success: true, cleanCount };
    } catch (error) {
      console.error('清理过期订单失败:', error);
      return { success: false, error };
    }
  }
} 